package com.h2wallet.newsapi.config;

import com.h2wallet.newsapi.common.constant.Constants;
import com.h2wallet.newsapi.common.exception.BusinessException;
import com.h2wallet.newsapi.modular.basic.service.EncryptService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class WebLogAscept {
        @Resource
        private EncryptService encryptService;






        /**
         * 定义一个切入点.
         * ("execution(public * com.kfit.*.web..*.*(..))")
         * 解释下：
         * 第一个 * 代表任意修饰符及任意返回值.
         * 第二个 * 任意包名
         * 第三个 * 代表任意方法.
         * 第四个 * 定义在web包或者子包
         * 第五个 * 任意方法
         * .. 匹配任意数量的参数.
         */
        @Pointcut("execution(public * com.h2wallet.newsapi.modular..*.controller..*.*(..))")
        public void webLog() {
        }

        @Around("webLog()")
        public Object round(ProceedingJoinPoint joinPoint) throws Throwable {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            /*try {*/
            //读取用户
            String token = request.getHeader(Constants.TOKEN_HEADER_NAME);
            int userId = 0;
            try {
                userId = encryptService.getUserIdFromToken(token);
            } catch (Exception ignored) {
            }

            //入参  value
            Object[] args = joinPoint.getArgs();
            //入参名称
            String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
            Map<String, Object> params = new HashMap<>();
            //获取所有参数对象
            for (int i = 0; i < args.length; i++) {
                if (null != args[i]) {
                    if (args[i] instanceof BindingResult) {
                        params.put(paramNames[i], "bindingResult");
                    } else {
                        params.put(paramNames[i], args[i]);
                    }
                } else {
                    params.put(paramNames[i], "无");
                }
            }
            log.info("URL : " + request.getRequestURL().toString());
            log.info("HTTP_METHOD : " + request.getMethod());
            log.info("IP : " + request.getRemoteAddr());
            log.info("USER_ID : " + userId);
            log.info("PARAMS : " + params);
            //切面返回值
            Object returnValue = joinPoint.proceed();

            return returnValue;
        }

        @AfterReturning("webLog()")
        public void doAfterReturning(JoinPoint joinPoint) {
            // 处理完请求，返回内容
            log.info("WebLogAspect.doAfterReturning()");
        }

    }